<?php

namespace App\Miya\Models;

use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Kalnoy\Nestedset\NodeTrait;
use Route;

class Classify extends Model
{
    use ModelTree, NodeTrait {
        NodeTrait::parent insteadof ModelTree;
        NodeTrait::children insteadof  ModelTree;
    }

    static public $states = [
        1 => '开启',
        2 => '关闭',
    ];
    protected $casts = [
        'extends' => 'json',
    ];
    protected $guarded = [];

    protected static function booted()
    {
        //删除分类前判断分类中是否存在信息,存在则无法删除
        static::deleting(function ($model) {
            $count = $model->infos()->count();
            if ($count > 0) {
                throw new \Exception('此分类下存在信息,无法删除!');
            }
        });
    }

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setOrderColumn('rank');
        $this->setTitleColumn('name');
    }

    public function getExtendsAttribute($value)
    {
        return json_decode($value, true) ?: [];
    }

    public function setExtendsAttribute($value)
    {
        $this->attributes['extends'] = json_encode($value, JSON_UNESCAPED_UNICODE);
    }

    public function keyword()
    {
        return $this->belongsTo(Keyword::class);
    }

    public function module()
    {
        return $this->belongsTo(Module::class);
    }

    public function infos()
    {
        return $this->hasMany(Info::class);
    }

    public function url()
    {
        $current = Route::currentRouteName();
        $prefix = explode('.', $current)[0];
        $data = [
            $this->module->tag,
            $this->tag
        ];
        $routeName = null;
        switch ($prefix) {
            case 'pc':
                $routeName = 'pc.classify';
                break;
            case 'area':
                $area = request()->route('area');
                $data = Arr::collapse([[$area->tag], $data]);
                $routeName = 'area.classify';
                break;
            case 'm':
                $routeName = 'm.classify';
                break;
            case 'domain_area':
                $area = request()->route('area');
                $data = Arr::collapse([[$area->tag], $data]);
                $routeName = 'domain_area.classify';
                break;
        }

        return route($routeName, $data);
    }
}
